<template>
    <div>
        <!-- 生产工单界面 -->
        <el-card v-if="showSearch" style="margin-bottom:20px ;">
            <!-- 搜查组 -->
            <el-form :model="workOrderForm">
                <el-row :gutter="24">
                    <el-col :span="6">
                        <el-form-item label="工单编码" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.workorderCode" placeholder="请输入工单编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="工单名称" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.workorderName" placeholder="请输入工单名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="来源单据" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.sourceCode" placeholder="请输入来源单据" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="产品编码" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.productCode" placeholder="请输入产品编码" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="6">
                        <el-form-item label="产品名称" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.productName" placeholder="请输入产品名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="客户编码" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.clientCode" placeholder="请输入客户编码" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="客户名称" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.clientName" placeholder="请输入客户名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="工单类型" :class="{ 'bold-label': true }">
                            <el-select v-model="workOrderForm.workorderType" placeholder="请选择工单类型" clearable
                                @change="handleStatusChange" style="width:240px">
                                <el-option label="自产" value="SELF" />
                                <el-option label="外协" value="OUTSOURCING" />
                                <el-option label="外购" value="OUTSOURCE" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="6">
                        <el-form-item label="需求日期" :class="{ 'bold-label': true }">
                            <el-date-picker v-model="workOrderForm.requestDate" value-format="YYYY-MM-DD" type="date"
                                placeholder="请选择需求日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item>
                            <el-button :icon="Search" type="primary" @click="onSearch">搜索</el-button>
                            <el-button :icon="Refresh" plain @click="onReset">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
        </el-card>

        <el-card>
            <!-- 按钮组 -->
            <el-row class="button-group">
                <el-col :span="10">
                    <div>
                        <el-button type="primary" :icon="Plus" plain @click="onAdd">新增</el-button>
                        <el-button type="success" :icon="EditPen" plain @click="onModify"
                            :disabled="isSingleRowSelected">修改</el-button>
                        <el-button type="danger" :icon="Delete" plain @click="onDelete"
                            :disabled="deleteDisabled">删除</el-button>
                        <el-button type="warning" :icon="Download" plain @click="onExport">导出</el-button>
                    </div>
                </el-col>
                <el-col :span="14">
                    <div class="button-right">
                        <el-tooltip contnet="隐藏搜索" placement="top">
                            <el-button :icon="Search" circle @click="toggleSearch" />
                        </el-tooltip>
                        <el-tooltip contnet="刷新" placement="top">
                            <el-button :icon="Refresh" circle @click="Reload" />
                        </el-tooltip>
                    </div>
                </el-col>
            </el-row>
            <!-- 表格组件 -->
            <el-table :data="tableData" row-key="workorderId" style="width: 100%" max-height="400px"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" :selectable="canSelectRow" />
                <el-table-column label="工单编码" width="200px" show-overflow-tooltip>
                    <template #default="{ row }">
                        <span style="color: #1890ff;" @click="showWorkOrder(row)">
                            {{ row.workorderCode }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="工单名称" prop="workorderName" width="100px" align="center" show-overflow-tooltip />
                <el-table-column label="工单类型" width="100px" align="center">
                    <template #default="{ row }">
                        <span v-if="row.workorderType == 'SELF'">自产</span>
                        <span v-else-if="row.workorderType == 'OUTSOURCE'">外协</span>
                        <span v-else>外购</span>
                    </template>
                </el-table-column>
                <el-table-column label="工单来源" width="100px" align="center">
                    <template #default="{ row }">
                        <span v-if="row.orderSource == 'ORDER'">客户订单</span>
                        <span v-else>库存备货</span>
                    </template>
                </el-table-column>
                <el-table-column label="订单编号" prop="sourceCode" width="100px" align="center" show-overflow-tooltip />
                <el-table-column label="产品编码" prop="productCode" width="100px" align="center" show-overflow-tooltip />
                <el-table-column label="产品名称" prop="productName" width="100px" align="center" show-overflow-tooltip />
                <el-table-column label="规格型号" prop="productSpc" show-overflow-tooltip align="center" />
                <el-table-column label="单位" prop="unitOfMeasure" width="100px" align="center" />
                <el-table-column label="工单数量" prop="quantity" width="100px" align="center" show-overflow-tooltip />
                <el-table-column label="调整数量" prop="quantityChanged" width="100px" align="center"
                    show-overflow-tooltip />
                <el-table-column label="已生产数量" prop="quantityProduced" width="100px" align="center"
                    show-overflow-tooltip />
                <el-table-column label="批次号" prop="batchCode" align="center" width="100px" show-overflow-tooltip />
                <el-table-column label="客户编码" prop="clientCode" width="100px" align="center" show-overflow-tooltip />
                <el-table-column label="客户名称" prop="clientName" align="center" show-overflow-tooltip />
                <el-table-column label="需求日期" prop="requestDate" width="140px" align="center" show-overflow-tooltip />
                <el-table-column label="单据状态" width="100px" align="center">
                    <template #default="{ row }">
                        <span v-if="row.status == 'PREPARE'">草稿</span>
                        <span v-else-if="row.status == 'CONFIRMED'">已确认</span>
                        <span v-else>已完成</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220px" align="center">
                    <template #default="scope">
                        <template v-if="scope.row.status === 'PREPARE'">
                            <el-button type="primary" plain text size="small" :icon="EditPen"
                                @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                            <el-button type="primary" plain text size="small" :icon="Delete"
                                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                        <template v-if="scope.row.status === 'CONFIRMED'">
                            <el-button type="primary" plain text size="small" :icon="Plus"
                                @click="handleAdd(scope.$index, scope.row)">新增</el-button>
                            <el-button type="primary" plain text size="small" :icon="Check"
                                @click="handleMarkAsCompleted(scope.$index, scope.row)">完成</el-button>
                        </template>
                        <template v-else>
                            <!-- 工单已完成，无其它操作 -->
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
                <el-pagination :current-page="workOrderForm.currentPage" :page-size="workOrderForm.pageSize"
                    :page-sizes="pageSizes" :total="pageResult.total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加工单弹窗 -->
        <AddDialog :addDialog="dialogVisbleAdd" @close-dialog="closeDialog" />

        <!-- 添加下级工单弹窗 -->
        <AddSubordinateDialog :addSubordinateDialog="dialogVisbleAddSubordinate" :Addvalue="Addvalue"
            @close-dialog="closeDialog" />

        <!-- 修改工单弹窗 -->
        <UpdateDialog :updateDialog="dialogVisbleUpdate" :UpdateValue="UpdateValue" @close-dialog="closeDialog" />

        <!-- 查询工单信息 -->
        <WorkOrderFindDialog :workorderdialog="dialogVisblefind" :Addvalue="Addvalue" @close-dialog="closeDialog" />

    </div>
</template>

<script setup>
import AddDialog from '@/components/ProcessTickets/AddDialog.vue';
import UpdateDialog from '@/components/ProcessTickets/UpdateDialog.vue';
import WorkOrderFindDialog from '@/components/ProcessTickets/WorkOrderFindDialog.vue';
import AddSubordinateDialog from '@/components/ProcessTickets/AddSubordinateDialog.vue';
import { reactive, ref, onMounted } from 'vue';
import { Search, Refresh, Delete, Download, Plus, EditPen, Check } from '@element-plus/icons-vue';
import { findWorkOrder, updateWorkOrder, removeWorkOrder } from '@/apis/lth/index';
import { ElMessage, ElMessageBox } from 'element-plus';
const dialogVisbleAdd = ref(false);//添加工单弹窗
const dialogVisbleAddSubordinate = ref(false);//添加工单弹窗
const dialogVisbleUpdate = ref(false);//修改工单弹窗
const dialogVisblefind = ref(false);//查看工单信息
let ids = ref([]); // 选中行的id数组
let HVal = ref([]); //选中行
const UpdateValue = ref({});//存储修改时选中行数据
const deleteDisabled = ref(true); // 删除按钮禁用状态,默认禁用
const isSingleRowSelected = ref(true); // 修改按钮禁用状态,默认禁用

let pageResult = ref({});//分页数据
let tableData = ref([]);//表格数据

const workOrderForm = reactive({
    currentPage: 1,
    pageSize: 10,
    workorderCode: '',
    workorderName: '',
    sourceCode: '',
    productCode: '',
    productName: '',
    clientCode: '',
    clientName: '',
    workorderType: '',
    requestDate: null
});
const Addvalue = reactive({//定义初始化数据属性
    workorderId: '',//工单id
    workorderCode: '',//工单编码
    workorderName: '',//工单名称
    orderSource: '',//来源类型
    sourceCode: '',// 单据来源（订单编码）
    workorderType: 'SELF',//工单类型
    productCode: '',//产品编码
    productName: '',//产品名称
    productSpc: '',//规格型号
    unitOfMeasure: '',//单位
    quantity: 0,//生产数量（订单数量）
    status: 'PREPARE',//单据状态，默认：草稿
    requestDate: '',//需求日期
    batchCode: '',//批次号
    parentId: '',//父级Id
    ancestors: '0',
    clientId: '',//客户Id
    clientCode: '',//客户编码
    clientName: '',//客户名称
    supplierCode: '',//供应商编码
    supplierName: '',//供应商名称
    remark: '',//备注
});

//工单类型
const handleStatusChange = (value) => {
    workOrderForm.workorderType = value
}

// 函数用于将日期对象格式化为 "yyyy-MM-dd" 字符串
const formatDate = (date) => {
    if (!date) return '';// 如果 date 是 null 或 undefined，则返回空字符串
    const d = new Date(date);
    // 检查是否是一个有效的日期
    if (isNaN(d.getTime())) {
        return ''; // 返回空字符串或根据需要处理无效日期
    }
    return d.toISOString().split('T')[0]; // "YYYY-MM-DD"
};

const loadList = () => {//查询工单总数据
    const params = { ...workOrderForm };
    params.requestDate = formatDate(params.requestDate);
    console.log(params);
    findWorkOrder(params).then((res) => {
        pageResult.value = res;
        tableData.value = pageResult.value.records
    })
}
// 分页大小
const pageSizes = [10, 20, 30, 40, 50];
//处理分页大小变化
const handleSizeChange = async (size) => {
    workOrderForm.pageSize = size;
    loadList();
}
//处理当前页码变化
const handleCurrentChange = async (currentPage) => {
    workOrderForm.currentPage = currentPage
    loadList();
}
//隐藏搜索条件
const showSearch = ref(true);
const toggleSearch = () => {
    showSearch.value = !showSearch.value;
}
//刷新
const Reload = () => {
    loadList();
}
//搜索功能
const onSearch = async () => {
    loadList();
}
//搜索条件重置
const onReset = async () => {
    Object.keys(workOrderForm).forEach(key => {
        workOrderForm[key] = null
    });
    loadList();
}
// 处理选中行变化,val 选中行的数组
const handleSelectionChange = (val) => {
    console.log(val)
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.workorderId) // 使用map方法过滤出选中行的roleId数组
    HVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        UpdateValue.value = { ...val[0] };//把选中的这条数据添加给修改数据
    }
}
const canSelectRow = (row) => {// 如果状态不是 PREPARE，则返回 false
    return row.status === "PREPARE";
}
//查看工单详情信息
const showWorkOrder = (row) => {
    Object.assign(Addvalue, row);
    dialogVisblefind.value = true;
}
//新增
const onAdd = () => {
    dialogVisbleAdd.value = true;
}
//单选修改
const onModify = () => {
    dialogVisbleUpdate.value = true;
}
//单行修改
const handleEdit = (index, row) => {//ElMessage.success('修改功能已触发');
    Object.assign(UpdateValue.value, row);
    dialogVisbleUpdate.value = true;
}
//选择删除
const onDelete = () => {
    ElMessageBox.confirm('确定要删除选中的订单吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        removeWorkOrder(ids.value).then((res) => {
            if (res === "成功") {
                ElMessage.success(`删除成功`);
                loadList();
            } else {
                ElMessage.success(`删除失败`);
            }
        });
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}
//单行删除
const handleDelete = (index, row) => {// console.log(row)
    ids.value.length = 0;
    ids.value.push(row.workorderId);
    ElMessageBox.confirm(`是否确认要删除订单编码为"${row.workorderCode}"吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        removeWorkOrder(ids.value).then((res) => {
            if (res === "成功") {
                ElMessage.success(`删除成功`);
                loadList();
            } else {
                ElMessage.success(`删除失败`);
            }
        });
    }).catch(() => {// ElMessage.info('已取消删除')
        console.log("已取消删除");
    })
};

const handleAdd = (index, row) => {//添加子级工单
    Addvalue.workorderId = row.workorderId;
    Addvalue.orderSource = row.orderSource;
    Addvalue.sourceCode = row.sourceCode;
    Addvalue.workorderType = row.workorderType;
    Addvalue.clientId = row.clientId,//客户Id
        Addvalue.clientCode = row.clientCode,//客户编码
        Addvalue.clientName = row.clientName,//客户名称
        // console.log("添加子级工单",Addvalue);
        dialogVisbleAddSubordinate.value = true;
};

const handleMarkAsCompleted = (index, row) => {//完成工单
    ElMessageBox.confirm('确认完成工单？一旦完成，此工单将无法继续报工！', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const updatedWorkOrder = Object.assign({}, Addvalue, row, { status: 'APPROVED' });
        //console.log("完成工单数据条：", updatedWorkOrder);
        updateWorkOrder(updatedWorkOrder).then(res => {//修改
            if (res == "成功") {
                ElMessage.success("修改成功");
                loadList();
            } else {
                console.log("更新工单失败");
            }
        });
    }).catch(() => {
        console.log("已取消完成工单");
    })
};

const onExport = () => {//导出
    ElMessage.success('导出功能已触发')
};

const closeDialog = () => {//弹窗关闭
    dialogVisbleAdd.value = false;
    dialogVisbleAddSubordinate.value = false;
    dialogVisbleUpdate.value = false;
    dialogVisblefind.value = false;
    loadList();
};

onMounted(() => {
    loadList();
});
</script>

<style scoped>
::v-deep .bold-label .el-form-item__label {
    font-weight: bold !important;
}

/* 使用 ::v-deep 选择器 */
::v-deep .el-table .el-table__header-wrapper thead tr th {
    background-color: #f8f8f9 !important;
    /* 你可以根据需要更改颜色 */
    color: #515a6e !important;
    /* 文字颜色 */
}

/* 如果需要更具体的控制，可以使用更详细的类名 */
::v-deep .el-table .el-table__header-wrapper thead tr th,
::v-deep .el-table .el-table__body-wrapper tbody tr td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

/* 使用 ::v-deep 选择器来穿透作用域样式 */
::v-deep.el-table th,
::v-deep .el-table td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.button-right {
    text-align: right;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    /* 将分页组件对齐到右侧 */
}
</style>
